require('grunt');
require('chromedriver');
require("selenidejs");

const chrome = require("selenium-webdriver/chrome");
const {Browser} = require('selenidejs');
const {Builder, Capabilities} = require('selenium-webdriver');
const {by, be} = require("selenidejs");

let browser;

module.exports = function (grunt) {

    grunt.registerTask('example', 'Just example', async function () {
            let done = this.async();
            // async:
            await openBrowser('https://studio.youtube.com/');
            let button = browser.element(by.xpath("//button[@id='avatar-btn']"));
            await button.should(be.visible);
            await button.click();
            await browser.element(by.xpath("//yt-formatted-string[text()='Сменить аккаунт']//ancestor::ytd-compact-link-renderer")).click();
            await quitBrowser();
            done();
        }
    )

    function openBrowser(url) {
        const chromeOptions = new chrome.Options();
        chromeOptions.addArguments("--user-data-dir=C:/Users/Myself/AppData/Local/Google/Chrome/User Data");
        const driver = new Builder().withCapabilities(Capabilities.chrome().setPageLoadStrategy("normal"))
            .setChromeOptions(chromeOptions)
            .build();
        browser = Browser.configuredWith()
            .driver(driver)
            .timeout(5000) // this is MAXIMUM wait time for elements to be visible or match conditions
            .build();

        return browser.open(url);
    }

    function quitBrowser() {
        return browser.quit();
    }
};